﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WaveEngine.Framework;
using WaveEngine.Framework.Animation;
using WaveEngine.Framework.Graphics;

namespace WaveEngine.Extensions.Behaviors
{
    public class BlinkBehavior : Behavior
    {
        [RequiredComponent]
        private Transform2D transform = null;

        private TimeSpan timer;
        private bool isFadeIn;

        public TimeSpan Duration { get; set; }
        public IEasingFunction EasingFunction { get; set; }
        public float MaxOpacity { get; set; }
        public float MinOpacity { get; set; }

        public BlinkBehavior(TimeSpan duration)
        {
            this.Duration = duration;
            this.MaxOpacity = 1;
            this.MinOpacity = 0;
        }


        protected override void Initialize()
        {
            base.Initialize();
            this.timer = TimeSpan.Zero;
            this.isFadeIn = true;
        }

        protected override void Update(TimeSpan gameTime)
        {
            if (this.timer >= this.Duration)
            {
                this.timer = TimeSpan.Zero;
                this.isFadeIn = !this.isFadeIn;
            }

            float elapsedTime = (float)(this.timer.TotalSeconds / this.Duration.TotalSeconds);

            if (this.EasingFunction != null)
            {
                elapsedTime = (float)this.EasingFunction.Ease(elapsedTime);
            }

            if (this.isFadeIn)
            {
                this.transform.Opacity = this.MinOpacity + (this.MaxOpacity - this.MinOpacity) * elapsedTime;
            }
            else
            {
                this.transform.Opacity = this.MinOpacity + (this.MaxOpacity - this.MinOpacity) * (1 - elapsedTime);
            }

            this.transform.DrawOrder = 1 - this.transform.Opacity;

            this.timer += gameTime;
        }
    }
}
